package com.blog.blog.util;

import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

@Component
public class RedisRateLimiter {

    private final RedissonClient redissonClient;

    public RedisRateLimiter(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    public boolean tryAcquire(String key, long rate, long interval, RateIntervalUnit unit) {
        RRateLimiter limiter = redissonClient.getRateLimiter("rate:limiter:" + key);
        if (!limiter.isExists()) {
            limiter.trySetRate(RateType.OVERALL, rate, interval, unit);
        }
        return limiter.tryAcquire();
    }
}


